var api = require('../config/api')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
function request(url,data={},method='GET'){
  return new Promise(function(resolve,reject){
    wx.request({
      url: url,
      data:data,
      method:method,
      header:{
        'Authorization':api.authorization,
        'Blade-Auth': wx.getStorageSync('userInfo')? "bearer "+wx.getStorageSync('userInfo').accessToken:''
      },
      success(res){
        if (res.data.code == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else {
            resolve(res.data);
          }
        }else if (res.data.code == 401){
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            });
        }

      },
      fail: function(err) {
        reject(err)
      }
    })
  })

}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}
function showSuccessToast(msg,duration) {
  wx.showToast({
    title: msg,
    image: '/static/images/wind-smile.png',
    duration:duration
  })
}
module.exports = {
  formatTime,
  showErrorToast,
  showSuccessToast,
  request
}
